<template>
  <!--  物料供应商关系-->
  <div class="content">
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" class="demo-form-inline">
        <el-form-item label="设备">
          <el-select
              v-model="searchParam.equipmentId"
              placeholder="请选择设备"
              clearable
              filterable
              style="width: 200px"
          >
            <el-option
                v-for="item in deviceList"
                :key="item.id"
                :label="item.equipmentCode"
                :value="item.id"
            >
              <span style="float: left">{{ item.equipmentCode }}</span>
              <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px;">
                {{ item.equipmentName }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 物料搜索 -->
        <el-form-item label="物料">
          <el-select
              v-model="searchParam.materialId"
              placeholder="请选择物料"
              clearable
              remote
              filterable
              :remote-method="getSearchMaterialList"
              style="width: 200px"
          >
            <el-option
                v-for="item in searchMaterialList"
                :key="item.id"
                :label="item.materialName"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="getList()">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">列表信息</div>
        <div class="pageTableButView">
          <el-button :icon="Plus" @click="handleAdd()">新建</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <el-table class="pageTableClass" :data="paginatedData" border height="calc(100vh - 320px)">
        <el-table-column label="序号" align="center" width="70">
          <template #default="scope">
            <!-- 下标 + 1，计算公式：当前页数 * 每页大小 + 当前行的索引 + 1 --> {{
              (pageSearch.current - 1) * pageSearch.pageSize
              + scope.$index + 1
            }}
          </template>
        </el-table-column>
        <el-table-column prop="equipmentCode" label="设备编码" align="center" min-width="200"/>
        <el-table-column prop="equipmentName" label="设备名称" align="center" min-width="200"/>
        <el-table-column prop="materialName" label="物料名称" align="center" min-width="250"/>
        <el-table-column prop="runtime" label="运行时长(min)" align="center" min-width="200"/>
        <el-table-column prop="theoreticalOutput" label="理论产量" align="center" min-width="200"/>
        <el-table-column prop="waitingTime" label="待机时长(min)" align="center" min-width="200"/>
        <el-table-column prop="createTime" label="创建时间" align="center" min-width="200" show-overflow-tooltip/>
        <el-table-column prop="createTime" label="状态" align="center" min-width="200" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.activate ? '已启用' : '禁用' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="230">
          <template #default="scope">
            <el-button
                @click="toggleActivate(scope.row)"
                :type="scope.row.activate ? 'danger' : 'success'"
                size="small"
            >
              {{ scope.row.activate ? '禁用' : '启用' }}
            </el-button>
            <el-button @click="handleEdit(scope.row)" type="text" size="small" plain
                       :icon="Edit">编辑
            </el-button>
            <el-button @click="handleDel(scope.row)" text type="danger" size="small"
                       :icon="Delete">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagePagination">
        <el-pagination background v-model:current-page="pageSearch.current"
                       v-model:page-size="pageSearch.pageSize" :page-sizes="[10, 20, 50, 100, 200, 500]"
                       layout="total, sizes, prev, pager, next" :total="pageTotal" @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"/>
      </div>
    </div>
    <!-- 弹窗表单 -->
    <el-dialog v-model="showCrud" :title="crudTitle" width="900px">
      <el-form :model="formData" label-width="150px" ref="ruleFormRef" :rules="rules" class="demo-ruleForm">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item required label="设备" prop="equipmentId">
              <!--							remote :remote-method="getCustomerList"-->
              <el-select v-model="formData.equipmentId" placeholder="请选择设备" style="width:300px" clearable
                         filterable>
                <el-option v-for="item in deviceList" :key="item.id" :label="item.equipmentCode"
                           :value="item.id">
                  <span style="float: left">{{ item.equipmentCode }}</span>
                  <span style="
                    float: right;
                    color: var(--el-text-color-secondary);
                    font-size: 13px;
                  "> {{ item.equipmentName }} </span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item required label="物料" prop="materialId">
              <el-select v-model="formData.materialId" placeholder="请选择物料" style="width:300px" clearable
                         remote :remote-method="getMaterialList" filterable>
                <el-option v-for="item in materialList" :key="item.id" :label="item.materialName"
                           :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运行时长(min)" required prop="runtime">
              <el-input-number v-model="formData.runtime" :min="0" style="width:300px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="理论产量" required prop="theoreticalOutput">
              <el-input-number v-model="formData.theoreticalOutput" :min="0" style="width:300px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="待机时长(min)" required prop="waitingTime">
              <el-input-number v-model="formData.waitingTime" :min="0" style="width:300px"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="showCrud = false">取消</el-button>
          <el-button type="primary" @click="handleSave(ruleFormRef)">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import {ref, reactive, computed, watch} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import axiosInstance from '@/utils/http/api';
import {Delete, Edit, Search, Share, Upload, Refresh, Plus, DocumentCopy} from '@element-plus/icons-vue';


const pageSearch = ref({
  current: 1,
  pageSize: 10
});

const pageTotal = ref(null);//页面总数
const isEdit = ref(false); // 是否编辑
const showCrud = ref(false); // 编辑/新建弹框
const searchParam = ref({});//页面检索条件
const crudTitle = computed(() => {
  return isEdit.value ? '编辑' : '新建';
});//弹出层标题
import type {ComponentSize, FormInstance, FormRules} from 'element-plus';

const ruleFormRef = ref<FormInstance>();

interface RuleForm {
  name: string;
  code: string;
  qualityWay: string;
  proportionNumber: string;
  qualityNumber: string;
  qualityType: string;
  qualityInterval: number;
  qualityIsLive: boolean;
  qualityRemark: string;
}


const originalFormData = reactive<RuleForm>({
  name: '',
  code: '',
  qualityWay: null,
  proportionNumber: 1,
  qualityNumber: 1,
  qualityType: '',
  qualityInterval: 1,
  qualityIsLive: true,
  qualityRemark: ''
});

let formData = reactive<RuleForm>(originalFormData);


const rules = reactive<FormRules<formData>>({
  materialId: [
    {required: true, message: '请选择物料', trigger: 'blur'}
  ],
  equipmentId: [
    {required: true, message: '请选择设备', trigger: 'blur'}
  ],
  runtime: [
    {required: true, message: '请输入运行时长', trigger: 'blur'}
  ],
  theoreticalOutput: [
    {required: true, message: '请输入理论产量', trigger: 'blur'}
  ],
  waitingTime: [
    {required: true, message: '请输入待机时长', trigger: 'blur'}
  ],
});


const toggleActivate = (row: any) => {
  const action = row.activate ? '禁用' : '启用';
  ElMessageBox.confirm(`确定${action}该记录吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    axiosInstance.put('/api/ttEquipmentProductOutputDtl/update', {
      ...row,
      activate: !row.activate
    }).then(res => {
      if (res.code !== 200) {
        ElMessage.error(res.message);
        return;
      }
      ElMessage.success(`${action}成功`);
      getList();
    });
  }).catch(() => {
    ElMessage.info('已取消操作');
  });
};

const materialList = ref([])
const customerList = ref([])

const getMaterialList = (e) => {
  if (e) {
    axiosInstance.post('/api/basedataMaterial/getPage', {
      current: 1,
      pageSize: 20,
      materialName: e
    }).then(res => {
      materialList.value = res.data.records
    })
  }
}

const getCustomerList = (e) => {
  if (e) {
    axiosInstance.post('/api/basedataSupplier/getAll', {
      name: e
    }).then(res => {
      customerList.value = res.data
    })
  }
}

// 获取搜索物料列表
const getSearchMaterialList = (query = '') => {
  if(query){
    axiosInstance.post('/api/basedataMaterial/getPage', {
      current: 1,
      pageSize: 20,
      materialName: query
    }).then(res => {
      searchMaterialList.value = res.data.records;
    });
  }

};



const paginatedData = ref<RuleForm[]>([]);

// 获取列表接口
const getList = () => {
  axiosInstance.post('/api/ttEquipmentProductOutputDtl/getPage', {
    ...searchParam.value,
    ...pageSearch.value
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        paginatedData.value = res.data.records;
        pageTotal.value = res.data.total;
      });
};

const deviceList = ref([])
const getOptions = () => {
  axiosInstance.post('/api/basedataEquipment/getAll', {})
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.warning(res.message);
          return false;
        }
        deviceList.value = res.data;
      });
}

const searchMaterialList = ref([])

const handleSizeChange = (e) => {
  pageSearch.value.pageSize = e;
  getList();
};

const handleCurrentChange = (e) => {
  pageSearch.value.current = e;
  getList();
};

// 重置搜索条件
const resetSearch = () => {
  searchParam.value = {};
  pageSearch.value.current = 1;
  // current.value = 1
  getList();
};

// 点击新建
const handleAdd = () => {
  isEdit.value = false;
  formData = reactive({});
  showCrud.value = true;
};

// 编辑
const handleEdit = (row: any) => {
  isEdit.value = true;
  getMaterialList(row.materialName)
  // getCustomerList(row.supplierName)
  Object.assign(formData, row);
  showCrud.value = true;
};

// 删除记录
const handleDel = (row: any) => {
  ElMessageBox.confirm('确定删除该条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    axiosInstance.delete(`/api/ttEquipmentProductOutputDtl/delete`, {
      data: {
        ids: [row.id]
      }
    }).then(res => {
      ElMessage.success('删除成功');
      getList(); // 刷新数据
    });


  });
};


// 弹框确定 确认新建 确定编辑
const handleSave = async (e: FormInstance | undefined) => {
  if (!e) return;
  await e.validate((valid, fields) => {
    if (valid) {
      if (isEdit.value) {
        // 编辑
        axiosInstance.put('/api/ttEquipmentProductOutputDtl/update', formData).then(res => {
          if (res.code != 200) {
            ElMessage.error(res.message);
            return false;
          }
          ElMessage.success('操作成功!');
          showCrud.value = false;
          getList(); // 刷新数据
        });
      } else {
        // formData.teamUserDTOS = {
        // 	userId: formData.teamUser
        // };
        // 新建
        formData.deptId = 1;
        formData.password = 1;

        axiosInstance.post('/api/ttEquipmentProductOutputDtl/save', formData).then(res => {
          if (res.code != 200) {
            ElMessage.error(res.message);
            return false;
          }
          ElMessage.success('操作成功!');
          showCrud.value = false;
          getList(); // 刷新数据
        });
      }

    }
  });
};


onMounted(() => {
  getList();
  axiosInstance.post('/api/basedataMaterial/getPage', {
    current: 1,
    pageSize: 20,
  }).then(res => {
    searchMaterialList.value = res.data.records;
  });
  axiosInstance.post('/api/basedataMaterial/getPage', {
    current: 1,
    pageSize: 20
  }).then(res => {
    materialList.value = res.data.records
  })
  axiosInstance.post('/api/basedataSupplier/getPage', {
    current: 1,
    pageSize: 20,
  }).then(res => {
    customerList.value = res.data.records
  })
  axiosInstance.post('/api/basedataEquipment/getAll', {})
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.warning(res.message);
          return false;
        }
        deviceList.value = res.data;
      });
});

</script>
<style scoped></style>
